package com.hapzxb.thread.singleton;

import java.util.concurrent.CompletableFuture;

public class SingletonDemo {
    private static volatile SingletonDemo instance = null;

    private SingletonDemo() {
        System.out.println(Thread.currentThread().getName() + "\t我是造方法singletonDemo()");
    }

    // DCL(Doouble check Lock.双端检锁机制)
    public static SingletonDemo getInstance() {
        if (instance == null) {
            synchronized (SingletonDemo.class) {
                if (instance == null) {
                    instance = new SingletonDemo();
                }
            }
        }
        return instance;
    }

    public static void main(String[] args) {
//        CompletableFuture
        // 单线程
//        System.out.println(SingletonDemo.getInstance());
//        System.out.println(SingletonDemo.getInstance());
//        System.out.println(SingletonDemo.getInstance());
//

        //并发多线程后，情况发生了很大的变化
        for (int i = 0; i < 1000; i++) {
            new Thread(() -> {
                SingletonDemo.getInstance();
            }, String.valueOf(i)).start();
        }

    }
}
